package 设计模式.d_原型模式;

import lombok.SneakyThrows;

import java.io.*;

/**
 * 实现了深拷贝
 *
 * @param <T>
 */
public abstract class Prototype1<T> implements Cloneable, Serializable {
    private static final long serialVersionUID = 1L;
    private String string;
    private T obj;

    // 浅复制
    @Override
    public Object clone() throws CloneNotSupportedException {
        Prototype proto = (Prototype) super.clone();
        return proto;
    }

    // 深复制
    @SneakyThrows
    public T deepClone() {
        // 写入当前对象的二进制流
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(this);
        // 读出二进制流产生的新对象 
        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bis);
        return (T) ois.readObject();
    }

//    public String getString() {
//        return string;
//    }
//
//    public void setString(String string) {
//        this.string = string;
//    }
//
//    public T getObj() {
//        return obj;
//    }
//
//    public void setObj(T obj) {
//        this.obj = obj;
//    }
}
